package com.ibiaoke.boss.service;

import com.ibiaoke.boss.dao.SysUserDao;
import com.ibiaoke.boss.entity.SysUser;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.utils.MD5Utils;
import com.ibiaoke.system.dao.ShopDao;
import com.ibiaoke.system.entity.Shop;
import com.ibiaoke.system.entity.ShopExample;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * Created by huhaichao on 2017/6/6.
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private ShopDao shopDao;

    @Override
    public SysUser login(String userName, String password) {
        if(StringUtils.isBlank(userName)){
            throw new ServiceException("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            throw new ServiceException("密码不能为空");
        }
        SysUser user = sysUserDao.getByName(userName);
        if(user==null){
            throw new ServiceException("用户不存在");
        }
        String md5Password = MD5Utils.getMD5String(password, user.getSalt());
        if(!Objects.equals(md5Password,user.getPassworld())){
            throw new ServiceException("用户名或密码错误");
        }
        removeSensitiveInfo(user);

        ShopExample example = new ShopExample();
        example.createCriteria().andUserIdEqualTo(user.getUserId());
        Shop shop = shopDao.getByExample(example);
        user.setShop(shop);

        return user;
    }


    public void removeSensitiveInfo(SysUser user){
        user.setPassworld(null);
        user.setSalt(null);
        user.setDelStatus(null);
        user.setCreateTime(null);
        user.setUpdateTime(null);
    }

    @Override
    public void RegisterUser(String userName, String password) {
        if(StringUtils.isBlank(userName)){
            throw new ServiceException("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            throw new ServiceException("密码不能为空");
        }
        SysUser user = sysUserDao.getByName(userName);
        if(user != null){
            throw new ServiceException("用户名已经注册");
        }
        SysUser sysUser = new SysUser();
        sysUser.setCreateTime(new Date());
        sysUser.setDelStatus((byte)0);
        sysUser.setUpdateTime(new Date());
        sysUser.setUserName(userName);

        sysUser.setSalt(UUID.randomUUID().toString());
        String md5Password = MD5Utils.getMD5String(password, sysUser.getSalt());
        sysUser.setPassworld(md5Password);
        sysUserDao.registerUser(sysUser);
    }
}
